<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="任务名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="开始时间">
                <el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd"
                    type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间">
                <el-date-picker v-model="daterangeEndTime" style="width: 240px" value-format="yyyy-MM-dd"
                    type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['exam:task:add']">新增每日一练</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['exam:task:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['exam:task:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['exam:task:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="主键，任务ID" align="center" prop="id" /> -->
            <el-table-column label="任务名称" align="center" prop="name" />
            <el-table-column label="开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="任务耗时（分钟）" align="center" prop="taskTime" />
            <!-- <el-table-column label="任务试卷ID，关联 t_task_exam_paper 表主键" align="center" prop="taskExamPaperId" /> -->
            <!-- <el-table-column label="创建者用户ID" align="center" prop="createBy" /> -->
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="更新者用户ID" align="center" prop="updateBy" /> -->
            <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['exam:task:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['exam:task:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改任务对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="人员类型" prop="peopleTypes">
                <el-select v-model="form.peopleTypes" multiple placeholder="请选择人员类型"
                           @change="handlePeopleTypeChange" filterable>
                  <el-option v-for="item in peopleTypeOptions" :key="item.value" :label="item.label"
                             :value="item.value" />
                </el-select>
                <el-button type="primary" size="small" @click="openBatchSelectDialog"
                           style="margin-left: 10px;">批量筛选</el-button>
              </el-form-item>
              <el-form-item label="关联题库">
                <div class="title-list-container">
                  <el-tag v-for="title in relatedTitles" :key="title" size="small" type="info">
                    {{ title }}
                  </el-tag>
                  <div v-if="!relatedTitles.length" class="no-data">
                    <span class="text-muted">请先选择人员类型</span>
                  </div>
                </div>
              </el-form-item>
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入任务名称" />
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd" placeholder="请选择任务开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd" placeholder="请选择任务结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="任务时间" prop="taskTime">
                    <div style="display: flex; align-items: center;">
                        <el-input-number v-model="form.taskTime" :step="10" style="flex: 1;" />
                        <span style="margin-left: 8px;">分钟</span>
                    </div>
                </el-form-item>

                <el-form-item label="题型配置" prop="questionConfig">
                    <el-table :data="questionTypeConfig" border style="width: 100%">
                        <el-table-column label="题型" align="center" prop="label" />
                        <el-table-column label="数量" align="center" width="200">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.count" :min="0" :max="10" size="small" />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
      <!-- 批量筛选人员类型弹窗 -->
      <el-dialog
        title="人员类型选择"
        :visible.sync="batchSelect.visible"
        width="800px"
        append-to-body
      >
        <el-form label-width="100px" label-position="left" style="padding: 0 10px;">

          <!-- 列表 -->
          <el-table
            :data="shortTitleList"
            highlight-current-row
            @current-change="handleShortTitleSelect"
            height="300"
            border
            style="margin-bottom: 15px; border-radius: 6px; overflow: hidden;"
          >
            <el-table-column
              label="试卷类型"
              prop="titleName"
              align="center"
              header-align="center"
            />
            <el-table-column
              label="人员类型"
              prop="peopleTypes"
              align="center"
              header-align="center"
            />
          </el-table>

          <!-- 输入框 -->
          <el-form-item label="人员类型" style="margin-top: 12px;">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入人员类型名称，以逗号分隔（中英文逗号均可）"
              v-model="batchSelect.input"
              style="font-size: 13px;"
            />
          </el-form-item>

          <!-- 提示 -->
          <div style="background: #fef4f4; color: #e74c3c; font-size: 12px; padding: 6px 10px; border-radius: 4px; margin: -4px 0 0 100px; width: calc(100% - 110px);">
            💡 点击上方列表可自动填充人员类型
          </div>

        </el-form>

        <!-- 底部按钮 -->
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button type="primary" @click="applyBatchSelect">确 定</el-button>
          <el-button @click="batchSelect.visible = false">取 消</el-button>
        </div>
      </el-dialog>

    </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/exam/task";
import { listPeopleTitleByPost,listPeopleTitleSummary } from "@/api/exam/peopleTitle";

export default {
    name: "Daily",
    dicts: ['exam_task_status', 'exam_question_type'],
    data() {
        // 自定义校验方法
        const validateQuestionConfig = (rule, value, callback) => {
            const hasQuestions = this.questionTypeConfig.some(item => item.count > 0);
            if (!hasQuestions) {
                callback(new Error('请至少配置一种题型'));
            }
            callback();
        };

        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 任务表格数据
            taskList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
          shortTitleList: [], // 这里存接口返回的 shortTitles 数据
          // 批量筛选相关
          batchSelect: {
            visible: false,
            input: ""
          },
            // 任务试卷ID，关联 t_task_exam_paper 表主键时间范围
            daterangeStartTime: [],
            // 任务试卷ID，关联 t_task_exam_paper 表主键时间范围
            daterangeEndTime: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                type: '1', // 固定为每日一练类型
                name: undefined,
                status: undefined
            },
            // 表单参数
            form: {
                type: '1', // 固定为每日一练类型
                name: undefined,
                id: null,
                startTime: null,
                endTime: null,
                taskTime: null,
                taskExamPaperId: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                deleted: null,
                peopleTypes: [], // 添加人员类型字段
                questionConfig: null // 添加题型配置字段
            },
            // 表单校验
            rules: {
                name: [
                    { required: true, message: "任务名称不能为空", trigger: "blur" }
                ],
                questionConfig: [
                    {
                        validator: (rule, value, callback) => {
                            const hasQuestions = this.questionTypeConfig.some(item => item.count > 0);
                            if (!hasQuestions) {
                                callback(new Error('请至少配置一种题型'));
                            } else {
                                callback();
                            }
                        }, trigger: 'change'
                    }
                ],
                createTime: [
                    { required: true, message: "创建时间不能为空", trigger: "blur" }
                ],
                updateTime: [
                    { required: true, message: "更新时间不能为空", trigger: "blur" }
                ],
            },
            // 新增配置项
            peopleTypeOptions: [], // 人员类型选项
            relatedTitles: [], // 关联的题库
            questionTypeConfig: [], // 题型配置
        };
    },
    created() {
        this.getList();
        this.loadPeopleTypes();
        this.initQuestionTypeConfig();
      this.getShortTitleList();
    },
    methods: {
        /** 查询任务列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            this.queryParams.type = '1';  // 每日一练类型为1

            if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
                this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0];
                this.queryParams.params["endStartTime"] = this.daterangeStartTime[1];
            }
            if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
                this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0];
                this.queryParams.params["endEndTime"] = this.daterangeEndTime[1];
            }
            listTask(this.queryParams).then(response => {
                this.taskList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                type: '1',
                name: undefined,
                id: null,
                startTime: null,
                endTime: null,
                taskTime: null,
                taskExamPaperId: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                deleted: null,
                peopleTypes: [], // 添加人员类型字段
            };
            this.resetForm("form");
            // 重置题型配置
            this.initQuestionTypeConfig();
            // 重置关联题库
            this.relatedTitles = [];
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.queryParams.taskType = '3'; // 确保查询时始终使用每日一练类型
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeStartTime = [];
            this.daterangeEndTime = [];
            this.resetForm("queryForm");
            this.queryParams.type = '1';
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.form.type = '1';
            this.open = true;
            this.title = "添加每日一练";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getTask(id).then(response => {
                this.form = response.data;
                // 1. 初始化人员类型选项
                this.loadPeopleTypes().then(() => {
                    // 2. 解析已有的配置
                    if (this.form.questionConfig) {
                        const config = JSON.parse(this.form.questionConfig);
                        // 设置人员类型
                        this.form.peopleTypes = config.peopleTypes || [];
                        // 设置关联题库
                        this.relatedTitles = config.titleNames || [];

                        // 初始化题型配置
                        this.initQuestionTypeConfig();
                        // 恢复题型配置
                        if (config.typeCount) {
                            this.questionTypeConfig.forEach(item => {
                                item.count = config.typeCount[item.type] || 0;
                            });
                        }
                    }
                });

                // 3. 处理日期格式，去掉时间部分
                if (this.form.startTime) {
                    this.form.startTime = this.form.startTime.split(' ')[0];
                }
                if (this.form.endTime) {
                    this.form.endTime = this.form.endTime.split(' ')[0];
                }

                this.open = true;
                this.title = "修改每日一练";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    // 构建提交数据
                    let submitData = { ...this.form };

                    // 处理日期，添加时间部分
                    if (submitData.startTime) {
                        submitData.startTime = submitData.startTime + " 00:00:00";
                    }
                    if (submitData.endTime) {
                        submitData.endTime = submitData.endTime + " 23:59:59";
                    }

                    // 将题型配置和人员类型信息一起转换为JSON字符串
                    submitData.questionConfig = JSON.stringify({
                        peopleTypes: this.form.peopleTypes,
                        titleNames: this.relatedTitles,
                        typeCount: this.questionTypeConfig.reduce((acc, curr) => {
                            if (curr.count > 0) {
                                acc[curr.type] = curr.count;
                            }
                            return acc;
                        }, {})
                    });
                    // 删除form中的peopleTypes字段,因为已经包含在questionConfig中了
                    delete submitData.peopleTypes;

                    if (submitData.id != null) {
                        updateTask(submitData).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addTask(submitData).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除任务编号为"' + ids + '"的数据项？').then(function () {
                return delTask(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('exam/task/export', {
                ...this.queryParams
            }, `task_${new Date().getTime()}.xlsx`)
        },
        // 初始化题型配置
        initQuestionTypeConfig() {
            if (this.dict.type.exam_question_type) {
                this.questionTypeConfig = this.dict.type.exam_question_type.map(item => ({
                    type: parseInt(item.value),
                    label: item.label,
                    count: 0
                }));
            }
        },
        // 加载人员类型选项
        async loadPeopleTypes() {
            try {
                const response = await listPeopleTitleByPost({
                    pageNum: 1,
                    pageSize: 10000,
                });
                // 提取不重复的 peopleType
                const types = [...new Set(response.rows.map(item => item.peopleType))];
                this.peopleTypeOptions = types.map(type => ({
                    label: type,
                    value: type
                }));
            } catch (error) {
                console.error('加载人员类型失败', error);
            }
        },
        // 处理人员类型变化
        async handlePeopleTypeChange(values) {
            if (!values.length) {
                this.relatedTitles = [];
                return;
            }

            try {
                const response = await listPeopleTitleByPost({
                    pageNum: 1,
                    pageSize: 10000,
                    peopleType: values.join(',')
                });
                // 获取新的题库名称列表
                const newTitles = response.rows.map(item => item.titleName);
                // 与现有列表合并并去重
                this.relatedTitles = [...new Set([...this.relatedTitles, ...newTitles])];
            } catch (error) {
                console.error('加载关联题库失败', error);
            }
        },
      // 获取 shortTitles 列表
      getShortTitleList() {
        listPeopleTitleSummary().then(res => {
          this.shortTitleList = res.rows
          // console.log('shortTitleList', this.shortTitleList)
        })
      },
      // 打开批量筛选对话框
      openBatchSelectDialog() {
        this.batchSelect.visible = true;
        this.batchSelect.input = "";
      },
      // 选中行事件
      handleShortTitleSelect(row) {
        if (row && row.peopleTypes) {
          this.batchSelect.input = row.peopleTypes
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          this.form.name = `${year}年${month}月${row.titleName}每日一练`;
        } else {
          this.batchSelect.input = ''
        }
      },
      // 应用批量筛选
      applyBatchSelect() {
        if (!this.batchSelect.input.trim()) {
          this.$message.warning('请输入人员类型名称');
          return;
        }

        // 处理输入的字符串，支持中英文逗号分隔
        const inputText = this.batchSelect.input.replace(/，/g, ',');
        const typeNames = inputText.split(',').map(name => name.trim()).filter(name => name);

        if (typeNames.length === 0) {
          this.$message.warning('未找到有效的人员类型名称');
          return;
        }

        // 匹配现有选项
        const matchedTypes = [];
        const unmatchedTypes = [];

        typeNames.forEach(typeName => {
          const option = this.peopleTypeOptions.find(opt => opt.label === typeName || opt.value === typeName);
          if (option) {
            matchedTypes.push(option.value);
          } else {
            unmatchedTypes.push(typeName);
          }
        });

        // 更新选择
        this.form.peopleTypes = matchedTypes;

        // 关闭弹窗
        this.batchSelect.visible = false;

        // 触发人员类型变化处理
        this.handlePeopleTypeChange(this.form.peopleTypes);

        // 显示结果
        if (unmatchedTypes.length > 0) {
          this.$message({
            type: 'warning',
            message: `成功匹配 ${matchedTypes.length} 项，未匹配 ${unmatchedTypes.length} 项`,
            duration: 3000
          });
        } else {
          this.$message({
            type: 'success',
            message: `成功匹配 ${matchedTypes.length} 项人员类型`,
            duration: 3000
          });
        }
      }
    },
    watch: {
        // 监听题型配置的变化
        questionTypeConfig: {
            handler(val) {
                // 当配置发生变化时，触发校验
                this.$nextTick(() => {
                    if (this.$refs.form) {
                        this.$refs.form.validateField('questionConfig');
                    }
                });
            },
            deep: true
        }
    }
};
</script>

<style scoped>
.el-slider {
    margin-top: 8px;
}

/* 调整滑块停止点的大小 */
:deep(.el-slider__stop) {
    width: 4px;
    height: 4px;
}

/* 调整滑块按钮的大小 */
:deep(.el-slider__button) {
    width: 12px;
    height: 12px;
}

/* 调整滑块轨道的度 */
:deep(.el-slider__runway) {
    height: 4px;
}

:deep(.el-slider__bar) {
    height: 4px;
}

.title-list-container {
    margin: 10px 0;
    min-height: 32px;
    max-height: 120px;
    overflow-y: auto;
    padding: 5px;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    background-color: #FAFAFA;
}

.title-list-container .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
}

.no-data {
    height: 32px;
    line-height: 32px;
    text-align: center;
    color: #909399;
}

/* 滚动条样式 */
.title-list-container::-webkit-scrollbar {
    width: 6px;
}

.title-list-container::-webkit-scrollbar-thumb {
    background-color: #909399;
    border-radius: 3px;
}

.title-list-container::-webkit-scrollbar-track {
    background-color: #F5F7FA;
}
</style>
